import { computed, onUnmounted, ref } from 'vue'
import dayjs from 'dayjs'
import duration from 'dayjs/plugin/duration' // 导入duration插件

// 扩展duration插件
dayjs.extend(duration)

export const useCountDown = () => {
  let timer = null
  const time = ref(0) // 剩余秒数

  // 格式化显示（核心修改点）
  const formatTime = computed(() => {
    return dayjs
      .duration(time.value, 'seconds')
      .format('mm分ss秒', { trim: false }) // 保持完整显示
  })

  // 启动倒计时
  const start = (currentTime) => {
    
    // 清除旧定时器
    if (timer) clearInterval(timer)
    
    // 初始化时间
    time.value = Number(currentTime)
     
    // 边界检查
    if (time.value <= 0) {
      time.value = 0
      return
    }

    timer = setInterval(() => {
      time.value--
      if (time.value <= 0) {
        clearInterval(timer)
        time.value = 0 // 防止负数
      }
    }, 1000)
  }

  // 组件卸载时清理
  onUnmounted(() => {
    timer && clearInterval(timer)
  })

  return {
    formatTime,
    start
  }
}